package com.atguigu.user.controller;

import com.atguigu.param.UserCheckParam;
import com.atguigu.param.UserLoginParam;
import com.atguigu.pojo.User;
import com.atguigu.user.service.UserService;
import com.atguigu.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Name: MyComputer
 * @ClassName UserController
 * @Description: 用户模块控制器
 * @date 2023/5/18 8:37
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userservice;

    @PostMapping("/check")
    //@Validated启动jsr303注解，BindingResult 获得校验结果，必须紧挨着UserCheckParam
    public R check(@RequestBody @Validated UserCheckParam userCheckParam, BindingResult result){
        boolean b = result.hasErrors();

        if (b){
            return R.fail("账号为空格，不可使用");
        }

        return userservice.check(userCheckParam);
    }

    @PostMapping("/register")
    public R register (@RequestBody @Validated User user, BindingResult result){
        boolean b = result.hasErrors();
        if (b){
            log.info("{},{}",user.getUserName(),user.getPassword());
            return R.fail("参数异常，不可注册");
        }
        return userservice.register(user);
    }

    @PostMapping("/login")
    public R login(@RequestBody @Validated UserLoginParam userLoginParam, BindingResult result){
        boolean b = result.hasErrors();
        if (b){
            return R.fail("参数异常，不可登录");
        }
        return userservice.login(userLoginParam);
    }
}
